from django.shortcuts import render, redirect, HttpResponse
from medical import models
from medical.utils.pagination import Pagination
from medical.utils.bootstrap import BootStrapModelForm
from django.core.exceptions import ValidationError
from medical.utils.pagination import Pagination
from medical.utils.form import SubModelForm


class Sub_dep_addModelForm(BootStrapModelForm):
    class Meta:
        model = models.sub_department
        fields = ["sub_dep_id", "sub_dep_name"]

    def clean_sub_dep_name(self):
        txt_name = self.cleaned_data["sub_dep_name"]
        # 验证次科室名称存在
        print(self.instance.pk)
        exists = models.sub_department.objects.exclude(sub_dep_id=self.instance.pk).filter(
            sub_dep_name=txt_name).exists()
        if exists:
            raise ValidationError("该科室已经存在")
        return txt_name

# def sub_dep__add(request):
#     """添加用户基于modelform"""
#     if request.method == "GET":
#         form = SubModelForm()
#         return render(request, 'sub_dep_add.html', {"form": form})
#
#     # 用户POST提交数据，数据校验。
#     form = SubModelForm(data=request.POST)
#     if form.is_valid():
#         # print(form.cleaned_data)
#         form.save()
#         return redirect('/sub_dep/list/')
#     # 校验失败（在页面上显示错误信息）
#     print(form.errors)


class Sub_dep_editModelForm(BootStrapModelForm):
    class Meta:
        model = models.sub_department
        fields = ["sub_dep_id", "sub_dep_name"]

    def clean_sub_dep_name(self):
        txt_name = self.cleaned_data["sub_dep_name"]
        # 验证次科室存在
        print(self.instance.pk)
        exists = models.sub_department.objects.exclude(sub_dep_id=self.instance.pk).filter(
            sub_dep_name=txt_name).exists()
        if exists:
            raise ValidationError("该次科室已经存在")
        return txt_name


# 医院表
def sub_dep_list(request):
    # 构造搜索
    data_dict = {}
    search_data = request.GET.get('search', "")
    if search_data:
        data_dict["sub_dep_name__contains"] = search_data

    queryset = models.sub_department.objects.filter(**data_dict)

    # 分页
    page_object = Pagination(request, queryset, page_size=5)

    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html(),
        "search_data": search_data
    }

    return render(request, 'sub_dep_list.html', context)


# forms.ModelForm 无样式
# # BootStrapModelForm 前端样式

def sub_dep_add(request):
    """添加次科室表"""
    # title = "添加次科室"
    # if request.method == "GET":
    #     form = Sub_dep_addModelForm()
    #     return render(request, 'template.html', {'form': form, "title": title})
    #
    # form = Sub_dep_addModelForm(data=request.POST)
    # if form.is_valid():
    #     form.save()
    #     return redirect('/sub_dep/list/')
    #
    # return render(request, 'sub_dep_add.html', {'form': form, 'title': title})
    if request.method == "GET":
        form = SubModelForm()
        return render(request, 'sub_dep_add.html', {"form": form})

    # 用户POST提交数据，数据校验。
    form = SubModelForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        form.save()
        return redirect('/sub_dep/list/')
    # 校验失败（在页面上显示错误信息）
    print(form.errors)


def sub_dep_edit(request, nid):
    """编辑次科室表"""
    title = "修改次科室"

    row_object = models.sub_department.objects.filter(sub_dep_id=nid).first()
    if not row_object:
        return redirect('/sub_dep/list/')

    if request.method == "GET":
        form = Sub_dep_editModelForm(instance=row_object)
        return render(request, 'template.html', {"form": form, "title": title})

    form = Sub_dep_editModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/sub_dep/list/')
    return render(request, 'template.html', {"form": form, "title": title})


def sub_dep_delete(request, nid):
    """删除次科室表"""
    models.sub_department.objects.filter(sub_dep_id=nid).delete()
    return redirect('/sub_dep/list/')
